package com.itheima.utils;

import com.aliyun.tea.utils.StringUtils;
import com.itheima.common.DefaultException;
import com.itheima.entity.Organization;
import com.itheima.enums.OrganizationEnum;
import com.itheima.service.OrganizationService;
import io.jsonwebtoken.lang.Collections;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <h1>检查权限工具类</h1>
 *
 * @author <a href="515857087@qq.com">叶世铭</a>
 * @since 2022/10/26
 */
@Component
public class CheckUtil {

    @Resource
    private OrganizationService organizationService;
    private static CheckUtil checkUtil;

    @PostConstruct
    public void init() {
        checkUtil = this;
        checkUtil.organizationService = this.organizationService;
    }

    public static String checkLogin() throws Exception {
        HttpServletRequest request;
        try {
            request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        } catch (RuntimeException var3) {
            return null;
        }
        String accessToken = request.getHeader("Authorization");
        if (StringUtils.isEmpty(accessToken)) {
            throw new DefaultException("请检查登录状态");
        }
        return JwtUtil.getUserId(accessToken);
    }

    /**
     * 判断A的权限和b的权限谁高
     * 如果A的权限高，返回true
     * 如果B的权限高，返回false
     * 同一个组织体系中
     *
     * @param aOrganizationId
     * @param bOrganizationId
     * @return
     */
    public static boolean checkRole(Integer aOrganizationId, Integer bOrganizationId) {
        Organization aOrganization = checkUtil.organizationService.getById(aOrganizationId);
        Organization bOrganization = checkUtil.organizationService.getById(bOrganizationId);
        if (aOrganization.getLevel() > bOrganization.getLevel()
                && aOrganization.getId() != OrganizationEnum.school.getOrganizationId()
                && aOrganization.getId() != OrganizationEnum.administrators.getOrganizationId()) {
            return false;
        }
        if (aOrganization.getLevel().equals(bOrganization.getLevel())) {
            return true;
        }
        ArrayList<Integer> childOrganizations = new ArrayList<>();
        ArrayList<Integer> bOrganizations = new ArrayList<>();
        bOrganizations.add(aOrganizationId);
        getChild(childOrganizations, bOrganizations);
        if (childOrganizations.contains(bOrganizationId)) {
            return true;
        }
        return false;
    }

    /**
     * 获取organizationId权限之下的所有organizationId存到childOrganizations
     *
     * @param childOrganizations
     * @param organizationId
     */
    public static void getChild(List<Integer> childOrganizations, List<Integer> organizationId) {
        if (Collections.isEmpty(organizationId)) {
            return;
        }
        ArrayList<Integer> mid = new ArrayList<>();
        organizationId.forEach(k -> {
            List<Organization> organizations = checkUtil.organizationService.lambdaQuery()
                    .eq(Organization::getParentId, k)
                    .isNull(Organization::getDeletedAt)
                    .list();
            List<Integer> childOrganizationIds = organizations.stream()
                    .map(Organization::getId)
                    .collect(Collectors.toList());
            childOrganizations.addAll(childOrganizationIds);
            mid.addAll(childOrganizationIds);
        });
        getChild(childOrganizations, mid);
    }


    /**
     * 检查文件后缀，Excel
     *
     * @param file
     * @throws DefaultException
     */
    public static void checkFileType(MultipartFile file) throws DefaultException {
        String fileName = file.getOriginalFilename();
        boolean suffixXls = fileName != null && fileName.endsWith(".xls");
        boolean suffixXlsx = fileName != null && fileName.endsWith(".xlsx");
        boolean suffixCsv = fileName != null && fileName.endsWith(".csv");
        if (!(suffixXls || suffixXlsx || suffixCsv)) {
            throw new DefaultException("文件格式错误，仅支持（.xls、.xlsx、.csv）后缀的文件！");
        }
    }


    /**
     * 检查文件后缀，图片
     *
     * @param file
     * @throws DefaultException
     */
    public static void checkImageType(MultipartFile file) throws DefaultException {
        String fileName = file.getOriginalFilename();
        boolean suffixJpeg = fileName != null && fileName.endsWith(".jpeg");
        boolean suffixJpg = fileName != null && fileName.endsWith(".jpg");
        if (!(suffixJpeg || suffixJpg)) {
            throw new DefaultException("文件格式错误，仅支持（.jpeg、.jpg）后缀的文件！");
        }
    }

    /**
     * 检查文件后缀，图片/视频
     *
     * @param files
     * @throws DefaultException
     */
    public static void checkImageType(List<MultipartFile> files) throws DefaultException {
        for (MultipartFile file :
                files) {
            String fileName = file.getOriginalFilename();
            boolean suffixJpeg = fileName != null && fileName.endsWith(".jpeg");
            boolean suffixJpg = fileName != null && fileName.endsWith(".jpg");
            boolean suffixMp4 = fileName != null && fileName.endsWith(".mp4");
            if (!(suffixJpeg || suffixJpg || suffixMp4)) {
                throw new DefaultException("文件格式错误，仅支持（.jpeg，.jpg，.mp4）后缀的文件！");
            }
        }
    }
}
